/**
 * jq dialog plugin by Markli
 */
(function() {

	var queue = {};

	var defaults = {
		dialogId: 'default_popup',
		html: '<div>Welcome You<div>',
		zIndex: 100,
		mask: true,
		duration: 0,
		timer: null,
		closeBtn: '.cancel',
		callback: function(){},
		closeCallback: function(){}
	}

	var zIndexMax = defaults.zIndex;

	var dialog = function(args) {
		
		var opts = _.extend(defaults, args);

		opts.zIndex = parseInt(opts.zIndex);
		opts.duration = parseInt(opts.duration);

		_.extend(this, opts);

		this.container = ($('#' + opts.dialogId).length > 0)  ? $('#' + opts.dialogId) : $('<div id="'+ opts.dialogId +'" class="dialog"></div>').prependTo('body');
		this.container.html(opts.html);
		this.show();

		// 队列处理
		queue[this.dialogId] = this;
	};
	
	dialog.fn = dialog.prototype = {
		show: function() {
			this.mask && App.blockUI();

			this.container.attr({
				target: 'target'
			}).css({
				zIndex: zIndexMax ++
			});

			// 触发open函数
			_.bind(this.callback, this);

			// 自动关闭处理
			if(this.duration){
				console.log('auto close');

				var that = this;

				if(this.timer){
					clearTimeout(this.timer);
					this.timer = null;
				} else {
					this.timer = _.delay(function(){
						that.close();
						that.closeCallback();
					}, this.duration)
				}
			}

			// bind关闭按钮
			var $close = this.container.find(this.closeBtn);
			$close.bind('tap', _.bind(this.close, this));
		},
		
		close: function() {

			this.container.attr({target: ''});
			App.unblockUI();

			_.bind(this.closeCallback, this);
			queue[this.dialogId] = null;
			delete queue[this.dialogId];
			this.container.remove();
		}
	};

	dialog.fn.constructor.prototype = dialog.fn;

	var uiBlocked = false;
	App.blockUI = function(opacity) {
		console.log(uiBlocked);

		if (uiBlocked) return;

		var $mask = ($('#mask').length > 0) ? $('#mask') : $('<div id="mask"></div>').prependTo('body');

		$mask.css({
			opacity: opacity ? " style='opacity:" + opacity + ";'" : ""
		}).attr({
			target: 'target'
		})

		$mask.bind("touchstart", function(e) {
			e.preventDefault();
		}).bind("touchmove", function(e) {
			e.preventDefault();
		});
		uiBlocked = true;
	};
	
	App.unblockUI = function() {
		uiBlocked = false;
		$('#mask').unbind("touchstart").unbind("touchmove").attr({target: ''});
	};

	App.dialog = function(opts){
		return new dialog(opts);
	}

})(window.App = window.App || {});

